#! /usr/bin/python
# encoding: utf-8

# xarabica - main module

# Copyright (C) 2010  Sulaiman A. Mustafa <sigtermer@gmail.com>
# This program is provided under the terms of the LGPL (version 3)
# http://www.gnu.org/licenses/lgpl.html

import xml.dom.minidom as xmldom
import xml.parsers.expat
import sys
import codecs

import xarabica_dicts #tag dictionary
tags=xarabica_dicts.htmlTags
attributes=xarabica_dicts.htmlAttributes


def getAttributes(dom, style):
	buff=" "
	styled=False
	for i, j in dom.attributes.items():
		try:
			i=attributes[i]
		except KeyError:
			pass
		if i=="style":
			j+=";"+style
			styled=True
		buff+=i+"='"+j+"'"
		buff+=" "
	if (not styled) and style:
		buff+=" style='"+style+"' "
		styled=True
	return buff

def HTMLgenerator(dom):
	string=""
	for i in dom.childNodes:
		if i.nodeType == 3: #Normal text
			string+=i.nodeValue
		elif i.nodeType == 1: #tag
			try:
				name=(tags[i.nodeName])[0]
				style=(tags[i.nodeName])[1]
				mono=(tags[i.nodeName])[2]
			except KeyError:
				name=i.nodeName
				style=""
				mono=False
			if mono:
				string+=u"<"+name+getAttributes(i, style)+">"				
			else:
				string+=u"<"+name+getAttributes(i, style)+">"+HTMLgenerator(i)+u"</"+name+">"
		else:
			string+=i.toxml()
	return string


def getDocRoot(dom):
	soup=dom.getElementsByTagName(u"مستند")
	if not len(soup):
		raise AssertionError(u"no مستند tag found!")
	return soup[0]
	
def stringToHTML(string):
	# to deal with bug http://bugs.python.org/issue4947
	if type(string)==unicode:
		string=string.encode('utf-8')
	return HTMLgenerator(getDocRoot(xmldom.parseString((string.replace("&", "&amp;")).strip())))




if __name__ == "__main__":
	#init check
	if sys.stdout.encoding != "UTF-8":
		sys.stderr.write("WARNING: STDOUT ENCODING IS NOT UTF-8")
	print "stdout encoding is "+str(sys.stdout.encoding)

	#input	
	if len(sys.argv) == 1:
		sys.stderr.write("reading from standard input\n")
		inputfile=sys.stdin
	elif len(sys.argv) == 3:
		if sys.argv[1] == "-":
			sys.stderr.write("reading from standard input\n")
			inputfile=sys.stdin
		else:
			sys.stderr.write(("reading from "+sys.argv[1]+"\n").encode("utf-8"))
			try:
				inputfile=codecs.open(sys.argv[1], "r", "utf-8")
			except IOError as error:
				sys.stderr.write(str(error)+"\n")
				sys.exit(1)
	else:
		sys.stderr.write(("error in number of args\n").encode("utf-8"))
		sys.exit(1)

	#output
	if len(sys.argv) == 1:
		sys.stderr.write("printing to standard output\n")
		outputfile=sys.stdout
	elif len(sys.argv) == 3:
		if sys.argv[2] == "-":
			sys.stderr.write("writing to standard output\n")
			outputfile=sys.stdout
		else:
			sys.stderr.write(("writing to "+sys.argv[2]+"\n").encode("utf-8"))
			try:
				outputfile=codecs.open(sys.argv[2], "w", "utf-8")
			except IOError as error:
				sys.stderr.write(str(error)+"\n")
				sys.exit(1)

	try:
		output=stringToHTML(inputfile.read())
	except xml.parsers.expat.ExpatError as err:
		sys.stderr.write(("\n"+"-"*60)+"\nError while trying to parse input file:\n"+str(err)+"\n")
		sys.exit(2)
	except AssertionError as err:
		sys.stderr.write(unicode(err).encode('utf-8')+"\n")
		sys.exit(2)
	except KeyboardInterrupt:
		sys.stderr.write("\ncaught keyboard interrupt.\n")
		sys.exit(3)

	if outputfile==sys.stdout:
		outputfile.write(output.encode('utf-8'))
	else:
		outputfile.write(output)
		




	
	

